package com.ztsoft.user.controller.file;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin("*")
@RequestMapping("/api")
public class FileUploadController {
    private static final String UPLOAD_DIR = "C:/dataFile/uploads/";
    // 假设服务器可以通过这个基础URL访问上传的文件
    private static final String FILE_ACCESS_URL = "/api/files/";

    // 确保上传目录存在
    static {
        Path dirPath = Paths.get(UPLOAD_DIR);
        if (!Files.exists(dirPath)) {
            try {
                Files.createDirectories(dirPath);
            } catch (IOException e) {
                throw new RuntimeException("Could not initialize storage", e);
            }
        }
    }
    @GetMapping("/download")
    public ResponseEntity<FileSystemResource> downloadFile2(@RequestParam String file) throws IOException {
        // 设置允许下载的文件目录前缀，避免安全风险
        String baseDir = UPLOAD_DIR;
        String filePath = baseDir + file;

        File downloadFile = new File(filePath);

//        if (!downloadFile.exists() || !downloadFile.getCanonicalPath().startsWith(baseDir)) {
//            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
//        }

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + downloadFile.getName());
        headers.add("Download-Filename", downloadFile.getName());

        return ResponseEntity.ok()
                .headers(headers)
                .body(new FileSystemResource(downloadFile));
    }
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> handleFileUpload(@RequestParam("file") MultipartFile file) {


        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();


            // 构建唯一的文件名以避免冲突
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

            // 构建完整的文件路径
            Path filePath = Paths.get(UPLOAD_DIR + uniqueFileName);

            // 将文件保存到指定位置
            Files.copy(file.getInputStream(), filePath);

            // 构造文件的访问URL
            String fileUrl = FILE_ACCESS_URL + uniqueFileName;

            // 返回原始文件名、唯一文件名和文件的访问URL
            Map<String, Object> response = new HashMap<>();
            response.put("originalFilename", originalFilename); // 用户上传的原始文件名
            response.put("uniqueFilename", uniqueFileName);     // 服务器上的唯一文件名
            response.put("fileUrl", fileUrl);

            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 可选：提供一个简单的文件下载接口
    @GetMapping("/files/{fileName:.+}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get(UPLOAD_DIR + fileName);
            byte[] fileContent = Files.readAllBytes(filePath);
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
                    .body(fileContent);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
    }
}